package com.lw.leetcode.str.a;

/**
 * 1816. 截断句子
 *
 * @Author liw
 * @Date 2021/11/6 21:47
 * @Version 1.0
 */
public class TruncateSentence {

    public static void main(String[] args) {
        TruncateSentence test = new TruncateSentence();
        String str = "Hello how are you Contestant";
        int k = 4;
        String s = test.truncateSentence(str, k);
        System.out.println(s + "&");
    }

    public String truncateSentence(String s, int k) {
        int length = s.length();
        int count = 0;
        for (int i = 0; i < length; i++) {
            if (s.charAt(i) == ' ') {
                count++;
                if (count == k) {
                    return s.substring(0, i);
                }
            }
        }
        return s;
    }
}
